﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.Model;
using HZ.Supervise.IBLL;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Admin
{
    public partial class UserList : BasePage
    {
        IBLL_User iu = BLLFactory.BLL_User();
        public string roleId;
        KeyOperationLogJG kj;
        string s = "";
        public UserList()
        {
            this.ModuleNo = Module.用户信息管理.ToString();
            this.PageOperateType = OperateType.主用户管理.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindUserByOthers();
            }
        }

        /// <summary>
        /// 根据条件读取用户
        /// </summary>
        private void BindUserByOthers()
        { 
            string strUserId = CurrentAccount.GetUser().UserID; 
            HZ.Supervise.Model.Query.OrgUsers user = new HZ.Supervise.Model.Query.OrgUsers();
            //需注释（监管中心端，卫生局端都可登陆。不可以写死） by：john
            user.RoleID = CurrentAccount.GetUser().UserRole.RoleID;
            user.IsAdmin = true;
            //if (this.ddlIsOnline.SelectedItem.Text != "(全部)")
            //{
            //    user.IsOnline = Convert.ToInt32(this.ddlIsOnline.SelectedItem.Value) == 1 ? true : false;
            //} 
            if (this.ddlIsUsing.SelectedItem.Text != "(全部)")
            {
                user.IsUsing = Convert.ToInt32(this.ddlIsUsing.SelectedItem.Value) == 1 ? true : false;
            } 
            if (!string.IsNullOrEmpty(this.txtUserId.Text))
            {
                user.UserID = this.txtUserId.Text;
            } 
            if (!string.IsNullOrEmpty(this.txtUserName.Text))
            {
                user.UserName = this.txtUserName.Text;
            } 
            if (!string.IsNullOrEmpty(this.txtLoginFrom.Text))
            {
                user.LastlogintimeFrom = Convert.ToDateTime(this.txtLoginFrom.Text);
            } 
            if (!string.IsNullOrEmpty(this.txtLoginTo.Text))
            {
                user.LastlogintimeTo = Convert.ToDateTime(this.txtLoginTo.Text);
            } 
            IList<HZ.Supervise.Model.View.OrgUsers> lu = new List<HZ.Supervise.Model.View.OrgUsers>();
            int TotalCount = 0;
            //验证方法是否能被正常调用
            try
            {
                lu = iu.GetOrgUsersByWhere(user, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out TotalCount);
                AspNetPager1.RecordCount = TotalCount;
                this.gvwUser.DataSource = lu;
                //if (lu.Count > 0)
                //{
                //    AddLog(string.Format("{0}在{1}查询了监管主用户数据", CurrentAccount.GetUser().UserID, DateTime.Now));
                //}
                this.gvwUser.DataBind();
            }
            catch (Exception ex)
            {
                PageError(ex.Message, "UserList.aspx");
            }
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            //重置首页
            this.AspNetPager1.CurrentPageIndex = 1;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            //this.gvwUser.EditIndex = -1;
            BindUserByOthers();
        }

        /// <summary>
        /// 执行锁定和解锁操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "IsUsing")
            {
                //string userId = e.CommandArgument.ToString();
                //List<string> userIds = new List<string>();
                //userIds.Add(userId);
                ////批量锁定
                //if (iu.LockUser(userIds))
                //{
                //    //重新加载列表
                //    this.BindUserByOthers();
                //}
                //else
                //{
                //    PageError("锁定/解锁用户失败！", "");
                //}
            }
        }
        /// <summary>
        /// 锁定用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatLock_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                //批量锁定
                if (iu.LockUser(userIds))
                { 
                    foreach (string u in userIds)
                    { 
                        s += u + ",";
                    }
                    s = s.Trim(',');
                    AddLog(string.Format("批量停用用户[{0}]成功!", s));
                    BindUserByOthers();
                }
                else
                {
                    PageError("锁定用户失败！", "");
                }
            }
        }

        /// <summary>
        /// 解锁用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatUnLock_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                //批量解锁
                if (iu.UnblockUser(userIds))
                {
                    foreach (string u in userIds)
                    {
                        s += u + ",";
                    }
                    s = s.Trim(',');
                    AddLog(string.Format("批量启用用户[{0}]成功!", s));
                    BindUserByOthers();
                }
                else
                {
                    PageError("解锁用户失败！", "");
                }
            }
        }

        /// <summary>
        ///  更新用户名称
        /// </summary>
        /// <param name="sender">事件发送源</param>
        /// <param name="e">事件参数</param>
        protected void gvwUser_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (Page.IsValid)
            {
                int rowIndex = e.RowIndex;
                string userId = this.gvwUser.DataKeys[rowIndex].Value.ToString();
                string strUserName = ((TextBox)this.gvwUser.Rows[rowIndex].FindControl("txtUserName")).Text.Trim();
                if (string.IsNullOrEmpty(strUserName))
                {
                    HZ.Web.WebUtil.Alert("用户名称不能为空！", this);
                    ((TextBox)gvwUser.Rows[rowIndex].FindControl("txtUserName")).Focus();
                    return;
                }
                User user = new User();
                user.UserID = userId;
                user.UserName = strUserName;
                if (iu.UpdateUser(user) == 1)
                { 
                    AddLog(string.Format("更改用户[{0}]名称成功!",userId));
                    //重新绑定列表
                    this.gvwUser.EditIndex = -1;
                    this.BindUserByOthers();
                }
                else
                {
                    PageError("更新失败！", "");
                }
            }

        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="sender">事件发送源</param>
        /// <param name="e">事件参数</param>
        protected void gvwUser_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.gvwUser.EditIndex = e.NewEditIndex;
            this.BindUserByOthers();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.gvwUser.EditIndex = -1;
            this.BindUserByOthers();
        }

        /// <summary>
        /// 初始化密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatResetPws_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    userIds.Add(arryUsers[i]);
                }

                if (iu.InitPassword(userIds, Constants.USER_DEFAULT_PWS))
                {
                    foreach (string u in userIds)
                    {
                        s += u + ",";
                    }
                    s = s.Trim(',');
                    AddLog(string.Format("批量初始化用户[{0}]密码成功!", s));
                    PageInfo("用户" + strChkUsers + "的密码已被初始化为" + Constants.USER_DEFAULT_PWS, "");
                }
                else
                {
                    PageError("密码初始化失败", "");
                }
            }

        }
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="msg"></param>
        private void AddLog(string msg)
        {
            kj = new KeyOperationLogJG();
            kj.OperationLogSerialID = Guid.NewGuid().ToString();
            kj.Operator = CurrentAccount.GetUser().UserID;
            kj.OrgID = CurrentAccount.GetUser().Org.OrgID;
            kj.OperateTime = DateTime.Now;
            kj.OperateMessage = msg;
            iu.AddKeyOperationLog(kj); 
        }
        /// <summary>
        /// 批量设置用户权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatSetOperate_Click(object sender, EventArgs e)
        {

            string strChkUsers = Request["chkUser"];
            string strRoleId = CurrentAccount.GetUser().UserRole.RoleID;
            string strRoleName = CurrentAccount.GetUser().UserRole.RoleName;

            if (!string.IsNullOrEmpty(strChkUsers) && !string.IsNullOrEmpty(strRoleId))
            {
                Response.Redirect("UserOperateBatch.aspx?uids=" + strChkUsers + "&rid=" + strRoleId + "&rname=" + HttpUtility.UrlEncode(strRoleName));
            }

        }

        protected void lbOprateClick(Object sender, CommandEventArgs e)
        {
            string str = e.CommandArgument.ToString();//得到前台绑定的参数

            Response.Redirect("UserOperate.aspx?uid=" + str + "");
        }

        protected void gvwUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //if (e.Row.Cells[1].Text == "jdjgqx")//由于jdjgqx是超级用户，所以我们不需要对其做权限修改
                //{
                //    //LinkButton lb = (LinkButton)e.Row.FindControl("lbOprate");
                //    //lb.Visible = false;//隐藏设置权限的按钮
                //    e.Row.Enabled = false;
                //}
                if (gvwUser.DataKeys[e.Row.RowIndex].Value.ToString() == "jdjgqx")//由于jdjgqx是超级用户，所以我们不需要对其做权限修改
                {
                    e.Row.Enabled = false;
                }
            }
        }
    }
}
 